package pe.com.itworth.ttsclient.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pe.com.itworth.ttsclient.infrastructure.Parser;
import pe.com.itworth.ttsclient.infrastructure.ParserGSON;
import pe.com.itworth.ttsclient.shared.AccountInfoDTO;
import pe.com.itworth.ttsclient.util.DataBaseHelper;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class AccountsMenuController extends Activity {

	private TextView accountNameTextView;
	private ListView menuListView;

	private static final int ALERT_EDIT = 110;

	public static DataBaseHelper myDbHelper;
	private Collection<AccountInfoDTO> accounts;

	private AccountInfoDTO account;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.accountsmenu);

		accountNameTextView = (TextView) findViewById(R.id.accountNameTextView);
		Gallery gallery = (Gallery) findViewById(R.id.accountAvatarGallery);
		menuListView = (ListView) findViewById(R.id.menuListView);

		vInitAccountNameTextView();
		vInitMenuListView();
		vInitDB();

		accounts = getAccountsJustWithAvatars();
		account = ((ArrayList<AccountInfoDTO>) accounts).get(0);
		accountNameTextView.setText("<" + account.getsDescription() + ">");

		menuListView
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					public void onItemClick(AdapterView<?> av, View v, int pos,
							long id) {
						vOnItemClicked(pos);
					}
				});

		gallery.setAdapter(new ImageAdapter(this));
		gallery.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView parent, View v, int position,
					long id) {
				vOnGalleryItemClicked(position);
			}
		});
	}

	private void vInitAccountNameTextView() {
		accountNameTextView.setText("");
	}

	private void vInitMenuListView() {
		Collection<Map<String, String>> menus = new ArrayList<Map<String, String>>();

		Map<String, String> menuItem1 = new HashMap<String, String>();
		menuItem1.put("icon", String.valueOf(R.drawable.mailbox2));
		menuItem1.put("description", "Mailbox");

		Map<String, String> menuItem2 = new HashMap<String, String>();
		menuItem2.put("icon", String.valueOf(R.drawable.settings));
		menuItem2.put("description", "Configuration");

		menus.add(menuItem1);
		menus.add(menuItem2);

		menuListView.setAdapter(new MenuAdapter(this, R.layout.accountmenuitem,
				(List<Map<String, String>>) menus));
	}

	private void vInitDB() {
		myDbHelper = new DataBaseHelper(this);

		try {
			myDbHelper.createDataBase();
		} catch (IOException ioe) {
			throw new Error("Unable to create database");
		}

		try {
			myDbHelper.openDataBase();
		} catch (SQLException sqle) {
			throw sqle;
		}
	}

	private Collection<AccountInfoDTO> getAccountsJustWithAvatars() {
		Collection<AccountInfoDTO> accounts = new ArrayList<AccountInfoDTO>();

		Cursor c = myDbHelper.executeQuery("select * from account");
		/* Get the indices of the Columns we will need */
		int iDescriptionColumn = c.getColumnIndex("t_description");
		int iImageColumn = c.getColumnIndex("t_image");
		int iHostColumn = c.getColumnIndex("t_host");
		int iUsernameColumn = c.getColumnIndex("t_username");
		int iPasswordColumn = c.getColumnIndex("t_password");
		int iProviderColumn = c.getColumnIndex("t_provider");

		/* Check if our result was valid. */
		if (c != null) {
			/* Check if at least one Result was returned. */
			if (c.getCount() > 0) {
				int i = 0;
				/* Loop through all Results */
				c.moveToNext();
				do {
					i++;
					/*
					 * Retrieve the values of the Entry the Cursor is pointing
					 * to.
					 */
					String sDescription = c.getString(iDescriptionColumn);
					String sImage = c.getString(iImageColumn);
					String sHost = c.getString(iHostColumn);
					String sUsername = c.getString(iUsernameColumn);
					String sPassword = c.getString(iPasswordColumn);
					String sProvider = c.getString(iProviderColumn);
					/*
					 * We can also receive the Name of a Column by its Index.
					 * Makes no sense, as we already know the Name, but just to
					 * shwo we can <img
					 * src="http://www.anddev.org/images/smilies/wink.png"
					 * alt=";)" title="Wink" />
					 */

					/* Add current Entry to results. */
					accounts.add(new AccountInfoDTO(null, sHost, sUsername,
							sPassword, sProvider, (int) Integer.decode(sImage),
							sDescription));
				} while (c.moveToNext());
			}
		}

		// /////////////////////////////////////////////////////////////////////
		return accounts;
	}

	private void vOnGalleryItemClicked(int position) {
		account = ((ArrayList<AccountInfoDTO>) accounts).get(position);
		accountNameTextView.setText("<" + account.getsDescription() + ">");
	}

	private void vOnItemClicked(int position) {
		Intent intent = null;

		if (position == 0) {
			Parser parser = new ParserGSON();

			intent = new Intent(this, MailboxTabPanelController.class);

			Bundle bundle = new Bundle();
			bundle.putString("account", parser.aCadena(account));
			intent.putExtras(bundle);
		}
		if (position == 1)
			intent = new Intent(this, ConfigurationTabPanelController.class);

		// Bundle bundle = new Bundle();
		// bundle.putString("doctor", vc.getDoctor());
		// bundle.putString("pregunta", vc.getDescripcion());
		// bundle.putString("fechaDePregunta", vc.getFechaDeEnvio());
		// bundle.putString("respuesta", vc.getRespuesta());
		// bundle.putString("fechaDeRespuesta", vc.getFechaDeEnvio());
		// intent.putExtras(bundle);
		this.startActivityForResult(intent, ALERT_EDIT);
	}

	public class ImageAdapter extends BaseAdapter {
		private Context context;
		private int itemBackground;

		public ImageAdapter(Context c) {
			context = c;
			// ---setting the style---
			TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
			itemBackground = a.getResourceId(
					R.styleable.Gallery1_android_galleryItemBackground, 0);
			a.recycle();
		}

		// ---returns the number of images---
		public int getCount() {
			return accounts.size();
		}

		// ---returns the ID of an item---
		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		// ---returns an ImageView view---
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView = new ImageView(context);
			imageView.setImageResource(((ArrayList<AccountInfoDTO>) accounts)
					.get(position).getiImage());
			imageView.setScaleType(ImageView.ScaleType.FIT_XY);
			imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
			imageView.setBackgroundResource(itemBackground);
			return imageView;
		}
	}

	private class MenuAdapter extends ArrayAdapter<Map<String, String>> {

		private Collection<Map<String, String>> items;

		public MenuAdapter(Context context, int iTextViewResourceId,
				Collection<Map<String, String>> items) {
			super(context, iTextViewResourceId,
					(ArrayList<Map<String, String>>) items);
			this.items = items;
			Log.i("MENUADAPTER:", " instanciated");
		}

		@Override
		public View getView(int iPosition, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.accountmenuitem, null);
			}
			Map<String, String> o = ((ArrayList<Map<String, String>>) items)
					.get(iPosition);
			if (o != null) {
				TextView tt = (TextView) v.findViewById(R.id.menuItemTextView);
				if (tt != null) {
					tt.setText(o.get("description"));
				}

				ImageView iv = (ImageView) v
						.findViewById(R.id.menuItemImageView);
				iv.setScaleType(ImageView.ScaleType.FIT_XY);
				iv.setImageResource(Integer.parseInt(o.get("icon")));

			} else {
				Log.i("MENUADAPTER", "object is NULL");
			}
			return v;
		}
	}

}